﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Newtonsoft.Json;
using Tools;
using JHStock.Update;
using System.Xml;
using JHStock.UserForm;
using System.Reflection;

namespace JHStock
{
	public partial class Form1 : Form
	{
        public Form1(JHConfig _jhconfig)
        {
			InitializeComponent();
            this._jhconfig = _jhconfig;
            this._cfg = new Form1Config();
            _CN = new ChineseName();
            this.TitleMsg = " ";
            _unablebtn = null;
            _FM = null;
        }
		private void Form1_Load(object sender, EventArgs e)
		{
            foreach (string str in JsonMainCWFX.GetNameList())
            {
                comboBoxProper.Items.Add(_CN.GetChineseName(str));
            }
            if (_jhconfig.Cloned)
                buttonDebugCustomSelect.Enabled = false;
            comboBoxMA.SelectedIndex = 0;
		}

        private void buttonDebugCustomSelect_Click(object sender, EventArgs e)
        {
            UpdateConfig();

            this.Hide();
            if (_jhconfig.Itemshows.ItemsShow.Count > 0)
            {
                CheckPath("data1");
                JHConfig jhdebug = _jhconfig.Clone("data1", _jhconfig.Itemshows.StocksByItemsShow());
                if (jhdebug.CheckReady())
                {
                    Form1 f = new Form1(jhdebug);
                    f.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("请先添加股票到自选");
            }
            this.Show();
        }
        private bool CheckPath(string newpath)
        {
            string workpath = _jhconfig.Jsconfig.pathconfig.WorkPath;
            workpath = workpath.Replace("\\Data\\","\\"+newpath+"\\");
            if (workpath.StartsWith("E:\\Git\\GitHome\\Source\\Project\\"))
            {
                try
                {
                    if (Directory.Exists(workpath))
                        Directory.Delete(workpath, true);
                    Directory.CreateDirectory(workpath);
                    Directory.CreateDirectory(workpath + "workpath\\");
                    Directory.CreateDirectory(workpath + "imgs\\");
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message);
                    return false;
                }
            }
            int i = 0;
            while (!Directory.Exists(workpath))
            {
                Thread.Sleep(1000);
                if (i++ > 3)
                    break;
            }
            return Directory.Exists(workpath);
        }
        private void buttonUpdateAll_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            _unablebtn = (Button)sender;
            _updateitemsindex = new List<string>();
            if(_cfg.MonthWeekDay)
                _updateitemsindex.AddRange( new string[]{"day", "week", "month"});
            if(_cfg.HourHalfMins)
                _updateitemsindex.AddRange( new string[]{"m1", "m5", "m15", "m30", "m60"});
            if(_updateitemsindex.Count==0)
                if(_cfg.Kdatatype!="")
                    _updateitemsindex.Add(_cfg.Kdatatype);
            if (_updateitemsindex.Count > 0)
            {
                _unablebtn.Enabled = false;
                UpdateAll();
            }
            else
            {
                MessageBox.Show("你还没有选择数据周期");
            }
        }
        private void buttonMA_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            this.Hide();
            try
            {
                FormMonit f = new FormMonit(_jhconfig, _jhconfig.ActiveStocksData);
                f.ShowDialog();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            this.Show();
        }
        private void buttonFinCW1_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            _unablebtn  = (Button)sender;
            if (!_jhconfig.IsUpdate)
            {
                _unablebtn.Enabled = false;
                _jhconfig.IsUpdateFin = true;
                System.Threading.Thread nonParameterThread =
                    new Thread(new ThreadStart(ThreadUpdateFin));
                nonParameterThread.Start();
            }
        }
        private void buttonExportStockCW_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            if (comboBoxProper.SelectedIndex == -1) return;
            string ChineseName = comboBoxProper.SelectedItem.ToString();
            string propertyname = _CN.GetProperName(comboBoxProper.SelectedItem.ToString());
            if (propertyname == "") return;
            ThreadShowMsg(
            DealClass.ExportCW(ChineseName, propertyname, _jhconfig.Itemshows.StocksByItemsShow(), _jhconfig.Stocks, _cfg.ReportByYears)
            );
            
        }
        private void buttonExportStock_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            DealClass DC = new DealClass(_jhconfig, _jhconfig.Stocks, this);
            DC.ExportKData(_jhconfig.Itemshows.StocksByItemsShow(),_jhconfig.ActiveStocksData);           
        }
        private void buttonExportFhSgData_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            DealClass DC = new DealClass(_jhconfig, _jhconfig.Stocks, this);
            DC.ExportFhKgData(_jhconfig.Itemshows.StocksByItemsShow());
        }
        private void buttonExportMacd_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            DealClass DC = new DealClass(_jhconfig, _jhconfig.Stocks, this);
            DC.ExportMacd(_jhconfig.Itemshows.StocksByItemsShow(),_jhconfig.ActiveStocksData,_cfg.OriginKdata);
        }
        private void ReCompute_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            DealClass DC = new DealClass(_jhconfig, _jhconfig.Stocks, this);
            int days = 0;
            if ( _cfg.ComputeByClosePrice &&  this._jhconfig.ActiveStocksData.KdataType == "dayly"   && textBoxExchangeTime.Text.Trim() != "")
            {
                try
                {
                    days = Convert.ToInt32(textBoxExchangeTime.Text);
                    if (days < 10 || days > 200)
                        days = 0;
                }
                catch
                {
                    days = 0;
                }
            }
            DC.ExportTestKData(_jhconfig.Itemshows.StocksByItemsShow(),_jhconfig.ActiveStocksData, !_cfg.ComputeByClosePrice,_cfg.CrossKdata, days);       
        }
        private void buttonDownloadsAllKdata_Click(object sender, EventArgs e)
        {
            //UpdateConfig();
            if (_FM == null)
                _FM = new FhsgsManage(_jhconfig);
            //if (File.Exists(_FM.localFindatafile))
            {
                //_FM.FhsgDatas
                //FhsgDatas FD = FhsgDatas.Load(_FM.localFindatafile);
                _FM.ThreadShowMsg = ThreadShowMsg;
                Thread nonParameterThread = new Thread(_FM.DownloadAll);
                nonParameterThread.Start();
            }
            //else
            //{
            //    _FM.ChangeToFormatFhsg();
            //}
        }
        private void buttonCreateMacd_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            ((Button)sender).Enabled = false;
            DealClass DC = new DealClass(_jhconfig, _jhconfig.Stocks, this);
            DC.CreateAllMacd(_jhconfig.ActiveStocksData);
            _jhconfig.Stocks.ResetMacdData();
            ((Button)sender).Enabled = true;
        }
		private void textBox1_TextChanged(object sender, EventArgs e)
		{
			string importtext = textBox1.Text;
			if (!checkBoxIDIndex.Checked)
			{
				List<string> find =_jhconfig.Itemshows.Items.FindAll(s => s.Contains(importtext.ToUpper()));
				if (find.Count > 0)
				{
					listBox1.Items.Clear();
					listBox1.Items.AddRange(find.ToArray());
				}
			}
			else
			{
				try
				{
					Stock s =_jhconfig.Stocks.StockByIndex(Convert.ToInt32(importtext));
					if (s != null)
					{
						listBox1.Items.Clear();
						string str =s.Code + "-" + s.Name + "(" + s.PYCode + ")" + "-" +  s.ID;
						listBox1.Items.Add(str);
					}
				}
				catch (Exception ex)
				{
					textBoxShow.Text = ex.Message;
				}
			}
		}
		private void listBox1_KeyUp(object sender, KeyEventArgs e)
		{
			if (listBox1.SelectedIndex == -1) return;
			if (e.KeyCode == Keys.D)
			{
				listBox1.Items.RemoveAt(listBox1.SelectedIndex);
			}else if(e.KeyCode == Keys.P || e.KeyCode ==Keys.O){
				if (listBox1.SelectedIndex == -1) return;
                ColorStyle cs = ColorStyles.classic;
                if (e.KeyCode == Keys.O)
                    cs = ColorStyles.print;
				string numcode = listBox1.SelectedItem.ToString().Substring(2, 6);
				Stock s = _jhconfig.Stocks.StockByNumCode(numcode);
                Bitmap bmp = StockDraw.DrawDailyLocal(s,_jhconfig.ActiveStocksData, cs);
				if (bmp!=null)				
                {				
					FormPictureBox f = new FormPictureBox(bmp);
					f.ShowDialog();
				}
			}
		}
		private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
            //ListBox lc = (ListBox)sender;
            //if (lc.SelectedIndex == -1) return;
            //string sqltemplate = "select * from [tablename] where [id] = [-id-] ";
            //string numcode = lc.SelectedItem.ToString().Substring(2, 6);
            //int index = _stocks.StockByNumCode(numcode).ID;
            //string sql = sqltemplate.Replace("[tablename]", "["+comboBoxCol.SelectedItem.ToString()+"]")
            //    .Replace("[-id-]", index.ToString());
            //if ("|bouns|Fin|NewFin|sinabouns|".Contains("|" + comboBoxCol.SelectedItem.ToString() + "|"))
            //    sql = sql.Replace("[id]", "stockid");
            //dgv.DataSource =_stocks.Gcfg.db.query(sql).Tables[0];
		}		
		private void buttonAddNextlist_Click(object sender, EventArgs e)
		{
			bool change = false;
			foreach (object o in listBox1.Items)
			{
				string s = (string)o;
                if (!_jhconfig.Itemshows.ItemsShow.Contains(s))
				{
                    _jhconfig.Itemshows.ItemsShow.Add(s);
					change = true;
				}
			}
			if (change)
			{
				listBox2.Items.Clear();
                listBox2.Items.AddRange(_jhconfig.Itemshows.ItemsShow.ToArray());
			}
		}
		private void buttonClearNextList_Click(object sender, EventArgs e)
		{
            if (_jhconfig.Itemshows.ItemsShow.Count > 0)
			{
                _jhconfig.Itemshows.ItemsShow.Clear();
				listBox2.Items.Clear();
			}
		}
        private void buttonImportCustom_Click(object sender, EventArgs e)
        {
            FormImportCustomStocks f = new FormImportCustomStocks(_jhconfig.Itemshows.Items, _jhconfig.Stocks);
            f.ShowDialog();
            if (f.ImportOK)
            {
                bool change = false;
                foreach (string txt in f.ImportItems)
                {
                    if (!_jhconfig.Itemshows.ItemsShow.Contains(txt))
                    {
                        _jhconfig.Itemshows.ItemsShow.Add(txt);
                        change = true;
                    }
                }
                if (change)
                {
                    listBox2.Items.Clear();
                    listBox2.Items.AddRange(_jhconfig.Itemshows.ItemsShow.ToArray());
                }
            }
        }
        private void UpdateConfig()
        {
            _cfg.MonthWeekDay = checkBoxYearMonthDay.Checked;
            if (comboBoxMA.SelectedIndex != -1)
                _cfg.Kdatatype = comboBoxMA.SelectedItem.ToString().ToLower();
            else
                _cfg.Kdatatype = "";
            _cfg.ReportByYears = radioButtonyears.Checked;
            _cfg.HasCWProper = comboBoxProper.SelectedIndex != -1;
            if(_cfg.HasCWProper)
                _cfg.CWProper = comboBoxProper.SelectedItem.ToString();
            _cfg.ComputeByClosePrice = radioButtonClos.Checked;
            _cfg.OriginKdata = checkBoxOrginKdata.Checked;
            _cfg.CrossKdata = checkBoxKDate.Checked;
            _jhconfig.SetKDataType(_cfg.Kdatatype);
            _jhconfig.SetCwfxType(_cfg.ReportByYears); 
        }
        private void UpdateAll()
        {
            if (!_jhconfig.IsUpdate)
            {
                _jhconfig.IsUpdateAllrunning = true;
                System.Threading.Thread nonParameterThread =
                    new Thread(new ThreadStart( ThreadUpdateAll ));
                nonParameterThread.Start();
            }
        }
        private void ThreadUpdateAll()
        {           
            foreach (string s in _updateitemsindex)
            {
                TitleMsg = "正在更新" + s + "数据 ";
                _jhconfig.SetKDataType(s);
                _jhconfig.ActiveStocksData.ThreadShowMsg = ThreadShowMsg;
                _jhconfig.ActiveStocksData.ActionMsg = ActionMsg;
                string InitDataMsg = _jhconfig.ActiveStocksData.InitData();
                TitleMsg = "完成更新" + s + "数据 ";
                ThreadShowMsg(InitDataMsg);
            }
            TitleMsg = "";
            ThreadShowMsg("已完成全部更新");
            ThreadCompleteRun();
            _jhconfig.IsUpdateAllrunning = false;
        }
        private void ThreadUpdateFin()
        {
            string s = "按报告期";
            if(_cfg.ReportByYears) 
                s = "按年度";
            TitleMsg = "正在更新财务数据-" + s  ;           
            _jhconfig.Updatefin.MaxThreadSum = 20;
            _jhconfig.Updatefin.ThreadShowMsg = ThreadShowMsg;
            _jhconfig.Updatefin.ThreadCompleteRun = ThreadCompleteRun;
            //_jhconfig.Updatefin.DealStocks = _stocks; 
            _jhconfig.Updatefin.DownLoadFinData();
            TitleMsg = "";
            ThreadShowMsg("已完成财务数据更新");
            ThreadCompleteRun();
            _jhconfig.IsUpdateFin = false;
        }
        public void CompleteRun()
        {
            if (_unablebtn != null)
                _unablebtn.Enabled = true;
        }
        public void ThreadHideMyself()
        {
            this.Invoke(  new CompleteDeleGate( HideMySelf));            
        }
        public void HideMySelf()
        {
            this.Hide();
        }
        public void ThreadActionMsg(string msg)
        {
            Invoke(new ActionDeleGate(ActionMsg), new object[] { msg });
        }
        public void ActionMsg(string msg)
        {
            if (msg.StartsWith("showexchangingtime-"))
                textBoxExchangeTime.Text = msg.Substring(19);

        }
        public void ThreadShowMsg(string msg)
        {
            this.Invoke(new ShowDeleGate(showfiletxt), new object[] { msg });
        }
        public void ThreadAppendMsg(string msg)
        {
            Invoke(new ShowDeleGate(showappendfiletxt), new object[] { msg });
        }
        public void ThreadCompleteRun()
        {
            Invoke(new CompleteDeleGate(CompleteRun));
        }       
        public void showfiletxt(string file)
        {
            file = TitleMsg + file;
            this.textBoxInfor.Text = file;
        }
        public void showappendfiletxt(string file)
        {
            this.textBoxInfor.Text += file;
        }

        private JHConfig _jhconfig;
        private Form1Config _cfg;
        private string TitleMsg;
        private ChineseName _CN;
        private Button _unablebtn;
        public DateTime _updatetime;
        private FhsgsManage _FM;
        private List<string> _updateitemsindex;

        private void buttonShowStockImag_Click(object sender, EventArgs e)
        {
            UpdateConfig();
            List<Stock> list = _jhconfig.Itemshows.StocksByItemsShow();
            if (_cfg.Kdatatype == "" || list.Count==0) return;
            this.Hide();
            try
            {
                FormShowStockImage f = new FormShowStockImage(_jhconfig, _cfg.Kdatatype, list);
                f.ShowDialog();
            }
            catch(Exception ee)
            {
                ThreadShowMsg(ee.Message);
            }
            this.Show();
        }

    }
    public class Form1Config
    {
        public bool MonthWeekDay { get; set; }
        public bool HourHalfMins { get; set; }
        public bool ReportByYears { get; set; }
        public string Kdatatype { get; set; }
        public string CWProper { get; set; }
        public bool HasCWProper { get; set; }
        public bool ComputeByClosePrice { get; set; }
        public bool CrossKdata { get; set; }
        public bool OriginKdata { get; set; }
    }
}

